import "dart:async";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/widgets/button/tap_text.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_form_builder/flutter_form_builder.dart";

class CodeTextField extends StatefulWidget {
  final Future<bool> Function() sendCode;

  const CodeTextField({super.key, required this.sendCode});

  @override
  State<CodeTextField> createState() => _CodeTextFieldState();
}

class _CodeTextFieldState extends State<CodeTextField> {
  int _countdown = 0;
  bool _loading = false;
  Timer? _timer;

  void _startCountdown() {
    setState(() => _countdown = 60);
    _timer = Timer.periodic(Durations.extralong4, (timer) {
      setState(() {
        _countdown -= 1;
        if (_countdown == 0) timer.cancel();
      });
    });
  }

  Future<void> _sendCode() async {
    try {
      setState(() => _loading = true);
      bool isSent = await widget.sendCode();
      if (isSent) {
        EasyLoading.showToast("验证码已发送");
        _startCountdown();
      }
      setState(() => _loading = false);
    } catch (error) {
      print(error);
      setState(() => _loading = false);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    Widget suffix = TapText(text: "获取验证码", onTap: _sendCode);
    if (_countdown != 0) {
      suffix = Text(
        "$_countdown秒后重试",
        style: const TextStyle(color: ThemeVars.colorTextTer),
      );
    } else if (_loading) {
      suffix = const SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(strokeWidth: 1),
      );
    }
    return FormBuilderTextField(
      decoration: InputDecoration(
        hintText: "验证码",
        suffixIcon: UnconstrainedBox(
          child:
              Padding(padding: const EdgeInsets.only(right: 20), child: suffix),
        ),
      ),
      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      keyboardType: TextInputType.number,
      name: "code",
    );
  }
}
